using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services;
using MaterialDesignThemes.Wpf;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Views;

/// <summary>
/// 项目工具窗口
/// </summary>
public partial class ProjectToolsWindow : Window
{
    private readonly IProjectToolsService _projectToolsService;
    private readonly ILogger<ProjectToolsWindow> _logger;
    private readonly int _projectId;
    private List<ProjectTool> _allTools = new();
    private List<ProjectTool> _filteredTools = new();
    private CancellationTokenSource? _executionCancellationSource;

    public ProjectToolsWindow(IServiceProvider serviceProvider, int projectId)
    {
        InitializeComponent();
        
        _projectToolsService = serviceProvider.GetRequiredService<IProjectToolsService>();
        _logger = serviceProvider.GetRequiredService<ILogger<ProjectToolsWindow>>();
        _projectId = projectId;
        
        Loaded += ProjectToolsWindow_Loaded;
    }

    private async void ProjectToolsWindow_Loaded(object sender, RoutedEventArgs e)
    {
        await LoadToolsAsync();
    }

    private async Task LoadToolsAsync()
    {
        try
        {
            StatusText.Text = "加载工具中...";
            
            var selectedProjectType = GetSelectedProjectType();
            _allTools = await _projectToolsService.GetAvailableToolsAsync(selectedProjectType);
            _filteredTools = new List<ProjectTool>(_allTools);
            
            DisplayTools();
            UpdateToolCount();
            
            StatusText.Text = "就绪";
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "加载工具失败");
            StatusText.Text = "加载工具失败";
            MessageBox.Show($"加载工具失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private string GetSelectedProjectType()
    {
        if (ProjectTypeComboBox.SelectedItem is ComboBoxItem item)
        {
            return item.Tag?.ToString() ?? "All";
        }
        return "All";
    }

    private void DisplayTools()
    {
        ToolsPanel.Children.Clear();
        
        var categories = _filteredTools.GroupBy(t => t.Category).OrderBy(g => g.Key);
        
        foreach (var category in categories)
        {
            // 添加分类标题
            var categoryHeader = new TextBlock
            {
                Text = category.Key,
                Style = (Style)FindResource("CategoryHeaderStyle")
            };
            ToolsPanel.Children.Add(categoryHeader);
            
            // 添加该分类下的工具
            var toolsGrid = new UniformGrid
            {
                Columns = 3,
                Margin = new Thickness(8, 0, 8, 16)
            };
            
            foreach (var tool in category.OrderBy(t => t.Name))
            {
                var toolCard = CreateToolCard(tool);
                toolsGrid.Children.Add(toolCard);
            }
            
            ToolsPanel.Children.Add(toolsGrid);
        }
    }

    private UIElement CreateToolCard(ProjectTool tool)
    {
        var card = new Card
        {
            Style = (Style)FindResource("ToolCardStyle"),
            Tag = tool
        };
        
        var grid = new Grid();
        grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
        grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
        grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
        grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
        
        // 工具图标和名称
        var headerPanel = new StackPanel { Orientation = Orientation.Horizontal };
        
        var icon = new PackIcon
        {
            Kind = GetPackIconKind(tool.Icon),
            Width = 24,
            Height = 24,
            VerticalAlignment = VerticalAlignment.Center,
            Foreground = (System.Windows.Media.Brush)FindResource("PrimaryHueMidBrush")
        };
        headerPanel.Children.Add(icon);
        
        var titleText = new TextBlock
        {
            Text = tool.Name,
            FontWeight = FontWeights.Medium,
            FontSize = 16,
            Margin = new Thickness(8, 0, 0, 0),
            VerticalAlignment = VerticalAlignment.Center
        };
        headerPanel.Children.Add(titleText);
        
        Grid.SetRow(headerPanel, 0);
        grid.Children.Add(headerPanel);
        
        // 工具描述
        var descriptionText = new TextBlock
        {
            Text = tool.Description,
            TextWrapping = TextWrapping.Wrap,
            Margin = new Thickness(0, 8, 0, 0),
            Foreground = (System.Windows.Media.Brush)FindResource("MaterialDesignBodyLight")
        };
        Grid.SetRow(descriptionText, 1);
        grid.Children.Add(descriptionText);
        
        // 工具信息
        var infoPanel = new StackPanel { Margin = new Thickness(0, 8, 0, 0) };
        
        if (tool.UsageCount > 0)
        {
            var usageText = new TextBlock
            {
                Text = $"使用次数: {tool.UsageCount}",
                FontSize = 12,
                Foreground = (System.Windows.Media.Brush)FindResource("MaterialDesignBodyLight")
            };
            infoPanel.Children.Add(usageText);
        }
        
        if (tool.LastUsedAt.HasValue)
        {
            var lastUsedText = new TextBlock
            {
                Text = $"最后使用: {tool.LastUsedAt.Value:MM-dd HH:mm}",
                FontSize = 12,
                Foreground = (System.Windows.Media.Brush)FindResource("MaterialDesignBodyLight")
            };
            infoPanel.Children.Add(lastUsedText);
        }
        
        Grid.SetRow(infoPanel, 2);
        grid.Children.Add(infoPanel);
        
        // 执行按钮
        var executeButton = new Button
        {
            Content = "执行",
            Style = (Style)FindResource("MaterialDesignRaisedButton"),
            HorizontalAlignment = HorizontalAlignment.Stretch,
            Margin = new Thickness(0, 8, 0, 0)
        };
        executeButton.Click += (s, e) => ExecuteTool_Click(tool);
        
        Grid.SetRow(executeButton, 3);
        grid.Children.Add(executeButton);
        
        card.Content = grid;
        return card;
    }

    private PackIconKind GetPackIconKind(string iconName)
    {
        return iconName switch
        {
            "FileConvert" => PackIconKind.FileDocument,
            "Robot" => PackIconKind.Robot,
            "Analytics" => PackIconKind.Analytics,
            "Backup" => PackIconKind.Backup,
            "CheckCircle" => PackIconKind.CheckCircle,
            _ => PackIconKind.Tools
        };
    }

    private async void ExecuteTool_Click(ProjectTool tool)
    {
        try
        {
            // 显示参数输入对话框
            var parameters = ShowParameterInputDialog(tool);
            if (parameters == null) return; // 用户取消
            
            // 显示进度对话框
            ShowProgressDialog($"执行 {tool.Name}");
            
            _executionCancellationSource = new CancellationTokenSource();
            
            // 执行工具
            var result = await _projectToolsService.ExecuteToolAsync(tool.Id, parameters);
            
            // 隐藏进度对话框
            HideProgressDialog();
            
            // 显示结果
            ShowExecutionResult(tool, result);
            
            // 刷新工具显示（更新使用统计）
            await LoadToolsAsync();
        }
        catch (Exception ex)
        {
            HideProgressDialog();
            _logger.LogError(ex, $"执行工具失败: {tool.Name}");
            MessageBox.Show($"执行工具失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private Dictionary<string, object>? ShowParameterInputDialog(ProjectTool tool)
    {
        if (!tool.Parameters.Any())
        {
            return new Dictionary<string, object>();
        }
        
        var dialog = new ToolParameterDialog(tool);
        var result = dialog.ShowDialog();
        
        return result == true ? dialog.GetParameters() : null;
    }

    private void ShowProgressDialog(string title)
    {
        ProgressTitle.Text = title;
        ProgressMessage.Text = "正在处理，请稍候...";
        ProgressDialogHost.IsOpen = true;
    }

    private void HideProgressDialog()
    {
        ProgressDialogHost.IsOpen = false;
    }

    private void ShowExecutionResult(ProjectTool tool, ToolExecutionResult result)
    {
        var resultDialog = new ToolExecutionResultDialog(tool, result);
        resultDialog.ShowDialog();
    }

    private void UpdateToolCount()
    {
        ToolCountText.Text = $"{_filteredTools.Count} 个工具可用";
    }

    private async void ProjectType_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (_allTools.Any())
        {
            await LoadToolsAsync();
        }
    }

    private void Search_TextChanged(object sender, TextChangedEventArgs e)
    {
        FilterTools();
    }

    private void FilterTools()
    {
        var searchText = SearchTextBox.Text?.ToLower() ?? "";
        
        if (string.IsNullOrEmpty(searchText))
        {
            _filteredTools = new List<ProjectTool>(_allTools);
        }
        else
        {
            _filteredTools = _allTools.Where(t => 
                t.Name.ToLower().Contains(searchText) ||
                t.Description.ToLower().Contains(searchText) ||
                t.Category.ToLower().Contains(searchText)
            ).ToList();
        }
        
        DisplayTools();
        UpdateToolCount();
    }

    private async void RefreshTools_Click(object sender, RoutedEventArgs e)
    {
        await LoadToolsAsync();
    }

    private void CustomTools_Click(object sender, RoutedEventArgs e)
    {
        // 打开自定义工具对话框
        MessageBox.Show("自定义工具功能开发中...", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
    }

    private async void ViewStatistics_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var statistics = await _projectToolsService.GetToolUsageStatisticsAsync(_projectId);
            var statisticsDialog = new ToolStatisticsDialog(statistics);
            statisticsDialog.ShowDialog();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取工具统计失败");
            MessageBox.Show($"获取工具统计失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void ShowHelp_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("项目工具帮助文档开发中...", "帮助", MessageBoxButton.OK, MessageBoxImage.Information);
    }

    private void CancelExecution_Click(object sender, RoutedEventArgs e)
    {
        _executionCancellationSource?.Cancel();
        HideProgressDialog();
        StatusText.Text = "操作已取消";
    }
}
